from fastapi import WebSocket
from typing import List
 
"""
创建工具管理类 处理服务端和客户端的交互
"""
class WebsocketManager:
    def __init__(self):
        # 初始化参数 记录活跃的客户端
        self.active_clients: List[WebSocket] = []
 
    async def connect(self, websocket: WebSocket):
        # 创建客户与服务端之间的连接 并记录下客户端
        await websocket.accept()
        self.active_clients.append(websocket)
 
    def disconnect(self, websocket: WebSocket):
        # 断开某个客户端的连接
        self.active_clients.remove(websocket)
 
    async def send_message_to_client(self, message: str, websocket: WebSocket):
        # 给客户端发送消息
        await websocket.send_text(message)
 
    async def broadcast(self, message: str):
        # 给所有客户端发送消息 广播
        for connection in self.active_clients:
            await connection.send_text(message)